# -*- coding: utf-8 -*-

from pymongo import MongoClient


class MongoDB():
    """
    输入一个数据库链接地址、数据库名称（字符串）、collection名称（字符串），不存在则创建
    """
    def __init__(self, uri, db, collection, pool_size=100):
        self._client = MongoClient(uri, maxPoolSize=pool_size)
        self.db = db
        self.collection = collection

    # 获取/创建mongo数据库
    def get_database(self):
        if self._client:
            return self._client.get_database(self.db)
        else:
            raise Exception("MongoClient connection failed")

    # 获取/创建mongo集合
    def get_collection(self):
        return self.get_database().get_collection(self.collection)
    
	# 查询所有集合
    def collection_names(self):
        return self.get_database().collection_names()
    
    # 添加一条数据
    def mongo_add(self, dic):
        self.get_collection().insert_one(dic)
	# 添加多条数据
    def mongo_addmany(self, dics):
        self.get_collection().insert_many(dics)
	
    # 查询数据
    def mongo_find(self, dic):
        return self.get_collection().find(dic)
    
     # 查询一条数据
    def mongo_findone(self, dic):
        return self.get_collection().find_one(dic)
    
    # 聚合查询
    def mongo_aggregate(self,dic):
        '''
        db = MongoDB('task31')
        dic = [
                {
                    "$group": {
                        "_id": {
                            "name": "$name",
                            "domain": "$domain",
                            "status": "$status"
                        },
                        "count": {
                            "$sum": 1
                        }
                    }
                }
            ]
        return db.mongo_aggregate(dic)
        '''
        return self.get_collection().aggregate(dic)

    # 更新数据
    def mongo_update(self, filters, updater):
        self.get_collection().update(filters, {"$set": updater})

    # 删除数据库
    def mongo_deldb(self):
        self._client.drop_database(self.db)

    # 删除集合
    def mongo_delcol(self):
        self.get_database().drop_collection(self.collection)

    # 删除所有文档
    def mongo_delall(self):
        self.get_collection().remove()

    # 删除文档
    def mongo_delone(self, dic):
        self.get_collection().remove(dic)
    
    # 创建索引索引
    def mongo_createIndex(self,filtername):
        '''
        db.getCollection("task62").createIndex({
            id: NumberInt("-1")
        }, {
            name: "taskid",
            unique: true
        })
        '''
        self.get_collection().ensure_index(filtername,unique=True)

    def close(self):
        self._client.close()
